#include "tilted_vwap.h"
#include "stock.h"
#include <algorithm>

#include <iostream>
using namespace std;

tilted_vwap::tilted_vwap (const std::string& _name, const std::string& _symbol, int hs, int ms, int ss, int he, int me, int se, int _exec, int _num_shares, int _total_trades, double _finish_price, double _stop_price, int _trade_interval_spread, int _trade_size_spread) 
: bot (_name, _symbol, hs, ms, ss, he, me, se, _exec, _num_shares, _finish_price, _stop_price), rnd_interval (-_trade_interval_spread / 100., _trade_interval_spread / 100.0), rnd_size (-_trade_size_spread / 100., _trade_size_spread / 100.0), crv ("vwap.crv"), editor ("vwap.ed"), lsnr (&sol)
{
  
  total_trades = _total_trades;
  trade_interval = avail_time * 1. / total_trades;
  
  VWAP = 0;
  
  sol (&crv);
  editor.add (&crv, &lsnr);
  pviewer = &editor;
  
}

tilted_vwap::~tilted_vwap () {
  editor.save ();
  crv.save ("vwap.crv");
}

int tilted_vwap::run (double secs) {
  
  if (bot::run (secs)) {
    //cout << "tilted_vwap = " << (value * 1. / position) << endl;
  }
  
  return 1;
  
}

int tilted_vwap::get_trade_size (double t) {
  
  double T = (t - start_time) * avail_time_1;
  stock* ps = get_stock_ptr (symbol);
  if (ps) {
    trade_size = max (0, (int) (ps->volume.value * sol (T) / 100.)); 
    return trade_size;
  }
  
  return 0;
  
}

double tilted_vwap::get_trade_interval () {
  return (max (0.01, trade_interval + rnd_interval () * trade_interval));
}

void tilt_listener::edited (curve_editor* ed, int i) {
  sol->update ();
}
